package com.test38_集合;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Stream接口
 * JDK1.8支持
 */
public class Demo10_Stream {

    @Test
    public void test1() {
        List<String> data = new ArrayList<>();
        Collections.addAll(data, "Java", "Javascript", "Python", "Ruby", "go", "C", "C++", "Sql");
        Stream<String> stream = data.stream();
        // filter()，对给定的数据执行过滤
        // collect(Collectors.toList())，满足过滤条件的数据，收集成一个新的List集合
        List<String> list = stream.filter((ele) -> ele.toLowerCase().contains("java")).collect(Collectors.toList());
        System.out.println(list);
    }

    /**
     * 实现部分数据内容的处理
     */
    @Test
    public void test2() {
        List<String> data = new ArrayList<>();
        Collections.addAll(data, "Java", "Javascript", "Python", "Ruby", "go", "C", "C++", "Sql");
        Stream<String> stream = data.stream();
        // skip()，跳过多少个
        // limit()，截取多少个
        List<String> list = stream.skip(3).limit(4)
                .filter((ele) -> ele.toLowerCase()
                .matches("(.*[jc].*)")).collect(Collectors.toList());
        System.out.println(list);
    }

    /**
     * 数据分析
     */
    @Test
    public void test3() {
        List<Order> orders = new ArrayList<>();
        orders.add(new Order("工程车玩具-vip版", 138.9, 500));
        orders.add(new Order("Java从入门到项目实战", 99.8, 5000));
        orders.add(new Order("VIP训练营", 13800.00, 60));
        Stream<Order> stream = orders.stream();
        DoubleSummaryStatistics vip = stream.filter((ele) -> ele.getName().toUpperCase().contains("VIP"))
                .mapToDouble((orderObject) -> orderObject.getPrice() * orderObject.getAmount())
                .summaryStatistics();
        System.out.println("【订单总量】" + vip.getCount());
        System.out.println("【订单总费用】" + vip.getSum());
        System.out.println("【商品平均价格】" + vip.getAverage());
        System.out.println("【商品最高价格】" + vip.getMax());
        System.out.println("【商品最低价格】" + vip.getMin());
    }
}

/** 订单类 */
class Order {
    private String name;
    private double price;
    private int amount;

    public Order(String name, double price, int amount) {
        this.name = name;
        this.price = price;
        this.amount = amount;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public int getAmount() {
        return amount;
    }
}
